package servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;

import utils.ItemsHelper;

/**
 * Servlet implementation class StatisticsServlet
 */
@WebServlet("/Statistics")
public class StatisticsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private static final String SOLD_ITEMS = "soldItems";
    private static final String UNSOLD_ITEMS = "unSoldItems";

    public StatisticsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json");
		try {			
			JSONObject jsonObject = new JSONObject();
			jsonObject.put(SOLD_ITEMS, 
					ItemsHelper.getNumberOfSoldItems()
					);
			jsonObject.put(UNSOLD_ITEMS, 
					ItemsHelper.getNumberOfItemsForSale()
					);
			response.getWriter().write(
					jsonObject.toString()
					);
		} catch (JSONException e) {
			e.printStackTrace();
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
	}



}
